package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.skivingcloud.admin.logutils.OperateLog;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.SysConfig;
import com.skivingcloud.admin.sys.service.SysConfigService;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Tag(name = "SysConfigController", description = "参数管理")
@RestController
@RequestMapping("/sysConfig")
public class SysConfigController {
    
    private static final Logger log = LoggerFactory.getLogger(SysConfigController.class);
    
    @Resource
    private SysConfigService sysConfigService;

    /**
     * 添加参数
     *
     * @param sysConfig 参数
     * @return {@code {code:0,message:"",data:true}} 添加成功，{@code {code:500,message:"",data:true}} 添加失败
     */
    @OperateLog(module="系统管理-基础配置-参数管理", description = "新增参数配置")
    @PostMapping("/save")
    @Operation(summary="保存系统参数配置信息表")
    @PreAuthorize("hasAuthority('sys:config:add')")
    public ReturnT<Boolean> save(@Validated @RequestBody SysConfig sysConfig) {
        try{
            SysConfig has = sysConfigService.getConfigValueByKey(sysConfig.getParamKey());
            if(has == null){
                return ReturnT.error("参数编码重复", false);
            }
            SecurityUser user = UserUtil.getCurrentUser();
            sysConfig.setId(UuidUtil.get32UUID());
            sysConfig.setCreator(user.getId());
            sysConfig.setCreateTime(LocalDateTime.now());
            return ReturnT.ok(sysConfigService.save(sysConfig));
        }catch(Exception e){
            if(e instanceof DuplicateKeyException){
                return ReturnT.error("参数编码重复", false);
            }
            log.error("新增参数失败", e);
            return ReturnT.error("新增参数失败", false);
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code {code:0,message:"",data:true}} 删除成功，{@code {code:500,message:"",data:true}} 删除失败
     */
    @OperateLog(module="系统管理-基础配置-参数管理", description = "删除参数配置")
    @PostMapping("/remove/{id}")
    @Operation(summary="根据主键系统参数配置信息表")
    @PreAuthorize("hasAuthority('sys:config:remove')")
    public ReturnT<Boolean> remove(@PathVariable(name="id") Serializable id) {
        try{
            return ReturnT.ok(sysConfigService.removeById(id));
        }catch(Exception e){
            log.error("删除失败", e);
            return ReturnT.error("删除失败", false);
        }
    }

    /**
     * 根据主键更新。
     *
     * @param sysConfig 参数
     * @return {@code {code:0,message:"",data:true}} 更新成功，{@code {code:500,message:"",data:true}} 更新失败
     */
    @OperateLog(module="系统管理-基础配置-参数管理", description = "修改参数配置")
    @PostMapping("update")
    @Operation(summary="根据主键更新系统参数配置信息表")
    @PreAuthorize("hasAuthority('sys:config:update')")
    public ReturnT<Boolean> update(@Validated @RequestBody SysConfig sysConfig) {
        try{
            SecurityUser user = UserUtil.getCurrentUser();
            sysConfig.setModUser(user.getId());
            sysConfig.setModTime(LocalDateTime.now());
            return ReturnT.ok(sysConfigService.updateById(sysConfig));
        }catch(Exception e){
            log.error("保存失败", e);
            return ReturnT.error("保存失败！", false);
        }
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("/getInfo/{id}")
    @Operation(summary="根据主键获取系统参数配置信息表")
    public ReturnT<SysConfig> getInfo(@PathVariable(name="id") Serializable id) {
        return ReturnT.ok(sysConfigService.getById(id));
    }

    /**
     * 分页查询。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @PostMapping("/page")
    @Operation(summary="分页查询系统参数配置信息表")
    @PreAuthorize("hasAuthority('sys:config:list')")
    public ReturnT<Page<SysConfig>> page(@RequestBody @Parameter(description="分页信息") PageParameter<SysConfig> parameter) {
        Page<SysConfig> page = sysConfigService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 根据参数编码获取参数值
     * @param key 参数编码
     * @return 参数值
     */
    @Operation(summary="根据参数编码获取参数值")
    @GetMapping("/getConfigValueByKey/{key}")
    public ReturnT<String> getConfigValueByKey(@PathVariable("key") String key){
        SysConfig config = sysConfigService.getConfigValueByKey(key);
        return ReturnT.ok(config.getParamValue());
    }
}
